<template>
  <div class="w-full h-[100vh] relative">
    <div class="text-[2rem] themeFontColor font-SemiBold pt-[28px]">
      <div
        class="flex flex-row justify-between items-center px-[32px] s4k:px-[32px] h-full"
      >
        <div class="flex flex-col">
          <span class="themeFontColor">Cameras</span>
          <span
            class="text-[1.167rem] themeFontDescColor font-Medium font-[400] mt-[3px] s2k:mt-[4px] s4k:mt-[6px]"
            >56 cameras</span
          >
        </div>
        <div class="flex flex-row">
          <div
            class="relative w-[154px] h-[41px] mr-[8px] s2k:w-[205px] s2k:h-[54px] s4k:w-[308px] s4k:h-[82px] s4k:mr-[16px]"
            @click="isEditCamerShow = !isEditCamerShow"
          >
            <div
              class="w-full h-full flex flex-row justify-center items-center themeButtonBgColor cursor-pointer rounded-md s4k:rounded-[16px]"
            >
              <span
                class="text-[1.167rem] themeFontColor font-Medium font-[400] ml-[6px] mr-[4px] s4k:mx-[8px]"
                >Edit Cameras</span
              >
              <svg-icon
                name="down"
                class="svgLayout s4ksvg s4k:ml-[6px] svg2kSize"
                width="20px"
                height="10px"
              ></svg-icon>
            </div>
            <div
              id="dropdown"
              ref="selectEditRef"
              :class="[
                'w-[154px] z-10 bg-gray-800 divide-y divide-gray-100 rounded-lg shadow dark:bg-gray-700 absolute top-[50px] left-0 bd-4b',
                's4k:w-[308px] s4k:top-[100px] s4k:rounded-[16px]',
                's2k:w-[205px] s2k:h-[54px] s2k:top-[60px]',
              ]"
              v-show="isEditCamerShow"
            >
              <ul
                class="text-[1.13rem] py-2 list-none bg-[var(--theme)] border border-solid border-[var(--theme-button-bg)] rounded-[8px] s4k:rounded-[16px]"
                aria-labelledby="dropdownDefaultButton"
              >
                <li
                  class="py-[3px] m-0 list-none text-[1.13rem] font-normal hover:bg-[var(--theme-hover)] s2k:py-[4px] s4k:py-[6px]"
                  @click="isEditModal"
                >
                  <a
                    href="javaScript:;"
                    class="text-[var(--theme-font-color)] block px-4 py-2 dark:hover:bg-gray-600 s4k:px-8 s4k:py-4 s4k:pr-0"
                    style="text-decoration: none"
                    >Add 3D Live URLs</a
                  >
                </li>
                <li
                  class="py-[3px] m-0 list-none text-[1.13rem] font-normal hover:bg-[var(--theme-hover)] s2k:py-[4px] s4k:py-[6px]"
                  @click="isDeteModal"
                >
                  <a
                    href="javaScript:;"
                    class="text-[var(--theme-font-color)] block px-4 py-2 dark:hover:bg-gray-600 s4k:px-8 s4k:py-4"
                    style="text-decoration: none"
                    >Delete Cameras</a
                  >
                </li>
              </ul>
            </div>
          </div>
          <div
            class="w-[168px] h-[41px] relative s2k:w-[224px] s2k:h-[54px] s4k:w-[336px] s4k:h-[82px]"
            @click="isAddCamerShow = !isAddCamerShow"
          >
            <div
              class="w-full h-full flex flex-row items-center justify-center bg-[#1C64F2] cursor-pointer rounded-md s4k:rounded-[16px]"
            >
              <svg-icon
                name="add"
                class="svgLogo svg2kSize ml-[3px] s4k:ml-[6px]"
                width="14px"
                height="14px"
              ></svg-icon>
              <span
                class="text-[1.167rem] text-white font-Medium font-[400] ml-[10px] mr-[4px] s4k:ml-[20px] s4k:mr-[12px]"
                >Add Camera</span
              >
              <svg-icon
                name="down"
                class="svgLogo svg2kSize s4ksvg"
                width="20px"
                height="10px"
              ></svg-icon>
            </div>
            <!-- Dropdown menu -->
            <div
              id="dropdown"
              ref="selectRulesRef"
              :class="[
                'w-[168px] z-10 bg-gray-800 divide-y divide-gray-100 rounded-lg shadow dark:bg-gray-700 absolute top-[50px] left-0 bd-4b',
                's4k:w-[336px] s4k:top-[100px] s4k:rounded-[16px]',
                's2k:w-[224px] s2k:h-[54px] s2k:top-[60px]',
              ]"
              v-show="isAddCamerShow"
            >
              <ul
                class="text-[1.167rem] py-2 list-none bg-[var(--theme)] border border-solid border-[var(--theme-button-bg)] rounded-[8px] s4k:rounded-[16px]"
                aria-labelledby="dropdownDefaultButton"
              >
                <li
                  class="py-[3px] m-0 list-none text-[1.13rem] font-normal hover:bg-[var(--theme-hover)] s2k:py-[4px] s4k:py-[6px]"
                  @click="isShowModal = true"
                >
                  <a
                    href="javaScript:;"
                    class="text-[var(--theme-font-color)] block px-4 py-2 dark:hover:bg-gray-600 s4k:px-8 s4k:py-4"
                    style="text-decoration: none"
                    >Manual Entry</a
                  >
                </li>
                <li
                  class="py-[3px] m-0 list-none text-[1.13rem] font-normal hover:bg-[var(--theme-hover)] s2k:py-[4px] s4k:py-[6px]"
                  @click="isShowModalTable = true"
                >
                  <a
                    href="javaScript:;"
                    class="text-[var(--theme-font-color)] block px-4 py-2 dark:hover:bg-gray-600 s4k:px-8 s4k:py-4"
                    style="text-decoration: none"
                    >Scan for Cameras</a
                  >
                </li>
              </ul>
            </div>
          </div>
        </div>
        <!--        <div class="w-[23.177vw] flex flex-row justify-between items-center h-[20px] s4k:h-[40px] s4k:mr-[31px]">
                  <fwb-input v-model="searchCamera" placeholder="Search" id="searchCamera" style="width: 100%">
                    <template #prefix>
                      <svg aria-hidden="true" class="w-5 h-5 themeFontDescColor dark:text-gray-400 s4k:w-10 s4k:h-10" fill="none" stroke="currentColor"
                        viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" stroke-linecap="round" stroke-linejoin="round"
                          stroke-width="2" />
                      </svg>
                    </template>
</fwb-input>
<button class="w-[90px] h-[38px] bg-[#1A56DB] text-white border-solid rounded-r-md border-[#1A56DB] border-[1px] cursor-pointer text-[14px]
                      s4k:w-[180px] s4k:h-[76px] s4k:text-[28px]">
  Search
</button>
</div>-->
      </div>
      <div
        id="mainRules"
        class="h-[calc(100vh_-_100px)] flex flex-row justify-between mt-[20px] s2k:h-[calc(100vh_-_133px)] s4k:h-[calc(100vh_-_200px)] s4k:mt-[40px] s4k:pl-[32px] s4k:ml-[-1%]"
        style="border-top: solid var(--grid) 1px"
      >
        <div class="flex flex-col">
          <div
            class="w-[full] h-[74px] flex flex-row justify-center items-center s2k:h-[97px] s2k:w-[434.7px] s4k:w-[652px] s4k:h-[148px]"
          >
            <div
              class="w-[90%] flex flex-row justify-between items-center h-[20px] s2k:h-[27px] s4k:h-[40px]"
            >
              <fwb-input
                v-model="searchCamera"
                placeholder="Search"
                id="searchCamera"
                style="width: 100%"
              >
                <template #prefix>
                  <svg
                    aria-hidden="true"
                    class="w-5 h-5 themeFontDescColor svg2kSize dark:text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                    />
                  </svg>
                </template>
              </fwb-input>
              <button
                class="w-[90px] h-[39px] border-solid rounded-l-0 rounded-r-md themeBorder text-[var(--theme-font-color)] border-[1px] cursor-pointer text-[1.167rem] s2k:w-[120px] s2k:h-[52px] s2k:rounded-r-[8px] s4k:w-[180px] s4k:h-[76px] bg-[var(--theme-button-bg)]"
              >
                Search
              </button>
            </div>
          </div>
          <div
            class="list w-[326px] h-full s2k:w-[435px] s4k:w-[652px]"
            style="border-right: solid var(--grid) 1px"
          >
            <!-- <div
              class="relative flex flex-row justify-between gridData-center hover:bg-[var(--theme-hover)] cursor-pointer border-solid border-b border-r border-[var(--grid)]"
              v-for="v in cameraList"
              :key="v.id"
              :class="cameraIndex === v.id ? 'themeHover' : ''"
              @click="cameraIndex = v.id"
            >
              <div
                class="flex flex-col justify-center gridData-start my-[8px] ml-[20px] s2k:my-[12px] s2k:ml-[25px] s4k:my-[16px] s4k:ml-[40px]"
              >
                <span
                  class="text-[1.167rem] themeFontColor font-Medium"
                >{{ v.name }}</span>
                <span
                  class="text-[1rem] themeFontDescColor font-Medium mt-[2px] s4k:mt-[4px]"
                >{{ v.location }}</span>
              </div>
              <div class="w-[20px] h-[20px] mr-[16px] my-auto mt-[3%] s4k:mt-[2%] s4k:mr-[5%]">
                <svg-icon :name="v.svg" width="20px" height="20px" class="svg2kSize s4ksvg"></svg-icon>
              </div>
            </div> -->
            <el-tree
              style="width: 100%"
              :allow-drop="allowDrop"
              :allow-drag="allowDrag"
              :data="treeData"
              draggable
              node-key="id"
              default-expand-all
              @node-drag-start="handleDragStart"
              @node-drag-enter="handleDragEnter"
              @node-drag-leave="handleDragLeave"
              @node-drag-over="handleDragOver"
              @node-drag-end="handleDragEnd"
              @node-drop="handleDrop"
              @mouseleave="showIndex = ''"
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <div style="width: 100%">
                  <el-input
                    v-if="data.editing"
                    v-model="data.label"
                    @blur="handleRenameBlur(data)"
                    @keyup.enter="handleRenameEnter(data)"
                    @click="handleInputClick"
                  ></el-input>
                  <div v-else class="relative">
                    <svg-icon
                      v-show="data.pid == 0"
                      name="add"
                      width="15px"
                      height="15px"
                      @click.stop="addNewNode(data)"
                      class="svgLogo cursor-pointer absolute top-[45%] right-0 transform -translate-y-1/2 -translate-x-1/2 s4k:right-[20px]"
                    ></svg-icon>
                    <div
                      v-show="data.pid !== 0 && data.children && showIndex == data.label"
                      class="h-full text-[1.16rem] text-[var(--theme-font-desc-color)] flex flex-row justify-center items-center absolute right-[3%] top-[50%] transform -translate-y-1/2"
                    >
                      <svg-icon
                        name="add"
                        width="15px"
                        height="15px"
                        @click.stop="addNewNode(data)"
                        class="svgLogo cursor-pointer mr-[15px] s2k:mr-[20px] s4k:mr-[30px] z-[999]"
                      ></svg-icon>
                      <svg-icon
                        name="edit"
                        width="15px"
                        height="15px"
                        class="svgLogo cursor-pointer"
                        @click.stop="handleNodeClick($event, data)"
                      ></svg-icon>
                    </div>
                    <div
                      v-if="data.children"
                      @contextmenu.prevent="showContextMenu(data)"
                      class="text-[1.16rem] text-[var(--theme-font-color)] font-SemiBold" @mouseover="handleNodeMouseOver(data)"
                      
                    >
                      {{ data.label }}

                    </div>
                    <div
                      v-else
                      style="display: flex; flex-direction: column; width: 100%"
                    >
                      <div
                        class="relative flex flex-row justify-between gridData-center hover:bg-[var(--layout-progress-active)] cursor-pointer"
                        v-for="v in cameraList"
                        :key="v.id"
                        @click="cameraIndex = v.id"
                        style="width: 100%"
                      >
                        <div
                          class="flex flex-col justify-center gridData-start my-[8px] s2k:my-[12px] s4k:my-[16px]"
                        >
                          <span
                            class="text-[1.167rem] themeFontColor font-Medium"
                            >{{ v.name }}</span
                          >
                          <span
                            class="text-[1rem] themeFontDescColor font-Medium mt-[2px] s4k:mt-[4px]"
                            >{{ v.location }}</span
                          >
                        </div>
                        <div
                          class="w-[20px] h-[20px] mr-[16px] my-auto mt-[5%] s4k:mt-[6%] s4k:mr-[5%]"
                        >
                          <svg-icon
                            :name="v.svg"
                            width="20px"
                            height="20px"
                            class="svg2kSize s4ksvg"
                          ></svg-icon>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
        <!--        <div class="w-[1300px] h-full s2k:w-[1733px] s4k:w-[2600px]">-->
        <!--          <Rules></Rules>-->
        <!--        </div>-->
        <div class="w-[67.81vw]">
          <Rules></Rules>
        </div>
      </div>
    </div>
    <!--    https://www.figma.com/design/n9f8l7oHcIAxpDtLJ2j0RL/Untitled?node-id=179-7896&t=4kmA1st6Gk4CZavD-0-->

    <!-- 模版弹窗 -->
    <ModalManually v-if="isShowModal" @close="close" />
    <!-- add Cameras -->
    <ModalScanning v-if="isShowModalTable" @close="closeTable" />
    <!-- Add 3D Live URLs -->
    <AddLiveURLs ref="EditRef" />
    <!-- Detele Cameras -->
    <DeteCameras ref="DeteRef" />
  </div>
</template>
<script setup>
import Rules from "./rules/index.vue";
import ModalManually from "./addCameras/ModalManually.vue";
import ModalScanning from "./addCameras/ModalScanning.vue";
import { onMounted, reactive, ref, watch, nextTick } from "vue";
import {
  FwbInput,
  FwbRadio,
  FwbDropdown,
  FwbButton,
  FwbModal,
  FwbToast,
} from "flowbite-vue";
import SvgIcon from "@/components/SvgIcon.vue";
import AddLiveURLs from "@/pages/Cameras/editCameras/AddLiveURLs.vue";
import DeteCameras from "@/pages/Cameras/editCameras/DeteCameras.vue";
import { message } from "ant-design-vue";

const searchCamera = ref("");
const cameraIndex = ref(1);
const cameraList = ref([]);
const isAddCamerShow = ref(false);
const isShowModal = ref(false);
const isShowModalTable = ref(false);
const isEditCamerShow = ref(false);
const EditRef = ref(false);
const DeteRef = ref(false);
const selectRulesRef = ref(null);
const selectEditRef = ref(null);
const isEditModal = () => {
  EditRef.value.showModal();
};
const isDeteModal = () => {
  DeteRef.value.showModal();
};
const Random = (arr) => {
  return arr[Math.floor(Math.random() * arr.length)];
};
const treeData = ref([
  {
    pid: 0,
    label: "All Group",
    editing: false,
    children: [
      {
        label: "Level one 1",
        editing: false,
        children: [
          {
            label: "Level two 1-1",
            editing: false,
            children: [
              {
                label: "Level three 1-1-1",
                editing: false,
              },
            ],
          },
        ],
      },
    ],
  },
]);
// 为每个节点添加索引作为id
function addIdToNodes(nodes, prefix = "") {
  return nodes.map((node, index) => ({
    ...node,
    id: `${prefix}${index + 1}`, // 使用前缀和索引生成id
    children: node.children
      ? addIdToNodes(node.children, `${prefix}${index + 1}-`)
      : undefined,
  }));
}
treeData.value = addIdToNodes(treeData.value);

const handleDragStart = (node, ev) => {
  console.log("drag start", node);
};
const handleDragEnter = (draggingNod, dropNode, ev) => {
  console.log("tree drag enter:", dropNode.label);
};
const handleDragLeave = (draggingNode, dropNode, ev) => {
  console.log("tree drag leave:", dropNode.label);
};
const handleDragOver = (draggingNode, dropNode, ev) => {
  console.log("tree drag over:", dropNode.label);
};
const handleDragEnd = (draggingNode, dropNode, dropType, ev) => {
  console.log("tree drag end:", dropNode && dropNode.label, dropType);
};
const handleDrop = (draggingNode, dropNode, dropType, ev) => {
  console.log("tree drop:", dropNode.label, dropType);
};
const allowDrop = (draggingNode, dropNode, type) => {
  if (dropNode.data.label === "Level two 3-1") {
    return type !== "inner";
  } else {
    return true;
  }
};
const allowDrag = (draggingNode) => {
  return !draggingNode.data.label.includes("Level three 3-1-1");
};
// 处理节点点击事件，显示重命名输入框
const handleNodeClick = async (event, data) => {
  event.preventDefault();
  showContextMenu(data);
  // const newValue = await window.prompt('请输入新的节点名称', data.name);
  // if (newValue !== null) {
  //   data.name = newValue;
  // }
  // updateNodeLabel(data, data.name);
};
const handleRenameBlur = (node) => {
  node.editing = false;
};
const handleInputClick = (event) => {
  event.stopPropagation();
};
const handleRenameEnter = (node) => {
  node.editing = false;
};
const showContextMenu = (node) => {
  console.log("node", node);
  treeData.value.forEach((item) => {
    item.editing = false;
  });
  if (!node.children) return false;
  node.editing = true;
};
const updateNodeLabel = (node, newName) => {
  const traverse = (nodes) => {
    for (const n of nodes) {
      if (n.id === node.id) {
        n.label = newName;
        break;
      }
      if (n.children) {
        traverse(n.children);
      }
    }
  };
  traverse(treeData.value);
};
// 添加新分组
const addNewNode = (data) => {
  let maxLevels = countNestedLevels(treeData.value)
  // console.log('maxLevels',maxLevels)
  if(maxLevels > 3 ) return message.warn("Creating a group succeeded");
  ElMessageBox.prompt("Please enter a group name", "New group", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    // inputPattern:
    //   /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    inputErrorMessage: "Invalid Group",
  })
    .then(({ value }) => {
      const newChild = { label: value, children: [] };
      if (!data.children) {
        data.children = [];
      }
      data.children.push(newChild);
      treeData.value = [...treeData.value];
      message.success("Creating a group succeeded");
    })
    .catch(() => {
      message.info("Cancel new group");
    });
};
// 鼠标移入显示添加修改
const showIndex = ref('')
const handleNodeMouseOver = (node) => {
  // console.log('Mouse entered:', node.label);
  showIndex.value = node.label
}
onMounted(() => {
  const element = document.getElementById("mainRules");
  const distanceToTop = element.getBoundingClientRect().top;
  console.log("distanceToTop", distanceToTop); // 133

  for (let i = 0; i < 1; i++) {
    cameraList.value.push({
      id: i + 1,
      name: `Camera 0${i + 1}`,
      location: `Lv ${i + 1}`,
      svg: Random(["type1", "type2", "type3"]),
      num: 0,
    });
  }
  nextTick(() => {
    document.addEventListener("mouseup", (e) => {
      if (selectRulesRef.value) {
        if (!selectRulesRef.value.contains(e.target)) {
          isAddCamerShow.value = false;
        }
      }
      if (selectEditRef.value) {
        if (!selectEditRef.value.contains(e.target)) {
          isEditCamerShow.value = false;
        }
      }
    });
  });
});
const close = (val) => {
  isShowModal.value = val;
};
const closeTable = (val) => {
  console.log(val);
  isShowModalTable.value = val;
};
const countNestedLevels = (data, level = 0) => {
  let maxLevel = level; // 记录当前最大层级
  for (const item of data) {
    if (item.children && item.children.length > 0) {
      const childLevel = countNestedLevels(item.children, level + 1);
      maxLevel = Math.max(maxLevel, childLevel);
    }
  }
  return maxLevel;
}
</script>

<style lang="scss" scoped>
#searchCamera {
  padding: 0;

  :deep(input) {
    padding-top: 0;
    padding-bottom: 0;
    height: 37px;
    background-color: var(--theme);
    border: solid var(--grid) 1px;
    font-size: 14px;
    font-family: Medium;
    color: var(--theme-font-color) !important;
    border-bottom-right-radius: 0;
    border-top-right-radius: 0;

    &:focus {
      box-shadow: inset 0 0;
    }
  }
}

#dropdown {
  :focus {
    box-shadow: none;
  }

  :deep(button) {
    width: 147px;
    height: 41px;
    cursor: pointer;

    :before {
      content: "";
    }

    span {
      display: none;
    }

    svg {
      display: none;
    }
  }
}

.s4ksvg {
  transform: scale(1.3) !important;
}

:deep(.el-tree-node__content) {
  font-size: 1.16rem !important;
  // background: gray;
  background: var(--theme-right);
  height: 50px;
  border-bottom: solid var(--grid) 1px;

  &:hover {
    background: var(--layout-progress-active);
  }
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: var(--theme-right);
}
@media screen and (min-width: 2560px) {
  .svg2kSize {
    transform: scale(1.4) !important;
  }

  #searchCamera {
    :deep(input) {
      height: 50.67px;
      padding-left: 40px;
      font-size: 20px;
    }
  }
  :deep(.el-tree-node__content) {
    height: 66.67px;
  }
}

@media screen and (min-width: 3840px) {
  .s4ksvg {
    transform: scale(2) !important;
  }

  #searchCamera {
    :deep(input) {
      height: 72px;
      font-size: 28px;
      padding-left: 60px;
    }
  }

  :deep(.el-tree-node__content) {
    height: 100px;

    .el-icon {
      margin: 0 15px !important;
      transform: scale(3) !important;
    }
  }
}

.list {
  overflow-y: scroll;
}

.list::-webkit-scrollbar {
  width: 3px;
}

.list::-webkit-scrollbar-thumb {
  background-color: var(--scrollbar-thumb);
  border-radius: 10px;
}

.list::-webkit-scrollbar-track {
  background-color: var(--scrollbar-track);
  border-radius: 10px;
}
</style>

<style lang="scss">
.el-message-box {
  background: var(--theme) !important;
  .el-message-box__title {
    color: var(--theme-font-color);
  }
  .el-message-box__message {
    color: var(--theme-font-desc-color);
  }
  .el-button {
    border: none;
    background: var(--theme-button-bg);
    color: var(--theme-font-color);
  }
  .el-button--primary {
    background: #1c64f2;
  }
}
.el-input__wrapper {
  padding-top: 0;
  padding-bottom: 0;
  height: 37px;
  background-color: var(--theme);
  border: solid var(--grid) 1px;
  box-shadow: none;
  font-size: 1.16rem;
  font-family: Medium;
  &:hover {
    box-shadow: none;
    border: solid var(--grid) 1px;
  }
}
.el-input__inner {
  font-size: 1.16rem;
  color: var(--theme-font-color);
  &:focus {
    border-color: transparent;
    box-shadow: none;
    outline: none;
  }
}
.is-hidden-arrow .el-tree-node__expand-icon {
  visibility: hidden;
}
@media screen and (min-width: 2560px) {
  .el-input__wrapper {
    height: 50px;
  }
  .ant-message-notice-content {
    transform: scale(1.3) !important;
    margin-top: 30px !important;
  }
  .el-message-box {
    transform: scale(1.3) !important;
  }
}
@media screen and (min-width: 3840px) {
  .el-input__wrapper {
    height: 74px;
  }
  .ant-message-notice-content {
    transform: scale(2) !important;
    margin-top: 50px !important;
  }
  .el-message-box {
    transform: scale(2) !important;
  }
}
</style>
